<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for=" child in cataList" :key="child.id" :label="child.cate_name" :value="child.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="loadArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table
        border
        stripe
        :data="artList"
        style="width: 100%">
        <el-table-column
          label="文章标题">
          <template v-slot='{row}'>
            <el-link type='primary' @click="showDetail(row.id)">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="cate_name"
          label="文章分类">
        </el-table-column>
        <el-table-column
          label="发表时间">
          <template v-slot='{row}'>
            {{formatDate(row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态">
        </el-table-column>
        <el-table-column
          label="操作">
         <template v-slot='{row}'>
            <el-button type="danger" size="mini" @click="del(row.id)">删除</el-button>
         </template>
        </el-table-column>
      </el-table>

       <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="q.pagenum"
          :page-sizes="[2, 3, 5, 10,20]"
          :page-size="q.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
    <el-dialog
      title="提示"
      :visible.sync="pubVisible"
      width="65%"
      >
      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option v-for=" item in cataList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor  v-model="pubForm.content"
                @blur="$refs.pubFormRef.validateField('content')">
          </quill-editor>

        </el-form-item >
        <el-form-item label="文章封面" prop="cover_img">
        <!-- 用来显示封面的图片 -->
          <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef" />
          <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="addSubmit" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item prop="state">
          <el-button type="primary" @click="hAdd('已发布')">发布</el-button>
          <el-button type="info" @click="hAdd('草稿')">存为草稿</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>
      <!-- 文章预览dialog -->
    <el-dialog
      title="文章预览"
      :visible.sync="detailVisible"
      width="65%">
        <h1 class="title">{{ artDetail.title }}</h1>
        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{formatDate( artDetail.pub_date )  }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>

        <!-- 分割线 -->
        <el-divider></el-divider>

        <!-- 文章的封面 -->
        <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

        <!-- 文章的详情 -->
        <div v-html="artDetail.content" class="detail-box"></div>

    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''

      },
      // dialog 发布文章弹框
      pubVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',
        cate_id: '',
        // 文章的内容
        content: '',
        cover_img: '',
        state: ''
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'change' }],
        content: [{ required: true, message: '请选择文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择文章图片', trigger: 'blur' }]
      },
      // 获取文章分类
      cataList: [],
      // 用户显示图片
      preview: '',
      // 文章发布列表
      artList: [],
      total: 0,
      artDetail: {},
      detailVisible: false
    }
  },
  methods: {
    // message发布文章提示框
    // handleClose(done) {
    //   this.$confirm('这样会导致数据丢失，确认关闭吗？', '提示', {
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       done()
    //     })
    //     .catch(() => {})
    // },
    // 添加文章封面
    addSubmit(e) {
      const file = e.target.files[0]
      // console.log(file)
      if (file) {
        this.preview = URL.createObjectURL(file)
        this.pubForm.cover_img = file
        this.$refs.pubFormRef.validateField('cover_name')
      } else {
        this.preview = ''
        // 清空input表单
        this.$refs.iptFile.value = ''
        this.pubForm.cover_img = ''
      }
    },
    // 发表文章
    async  hAdd(state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        const fd = new FormData()
        for (const k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        const { data: res } = await this.$http.post('/my/article/add', fd)
        // console.log(res)
        // 提醒用户
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 关闭dalaog
        this.pubVisible = false
        // 重置表单
        this.$refs.pubForm.resetFields()
        // 清空图片
        this.preview = ''
        this.loadArtList()
      })
    },
    // 获取文章分类
    async  loadCateList() {
      const { data: res } = await this.$http.get('my/cate/list')
      this.cataList = res.data
    },
    // 获取文章发布列表
    async loadArtList() {
      // 获取发布文章列表
      const { data: res } = await this.$http.get('/my/article/list', { params: this.q })
      // 存入data中
      this.artList = res.data
      this.total = res.total
    },
    // 时间装换
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 删除文章
    del(id) {
      // 提示用户
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 发送请求删除数据
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        // 判断页面是否能正常跳转
        if (this.artList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }
        // 重新获取页面数据
        this.loadArtList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.q.pagesize = val
      this.q.pagenum = 1
      // 重新获取数据
      this.loadArtList()
    },
    handleCurrentChange(val) {
      this.q.pagenum = val
      this.loadArtList()
    },
    // 重置文章列表数据
    resetForm() {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.loadArtList()
    },
    async  showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return
      this.artDetail = res.data
      this.detailVisible = true
      // console.log(res.data)
    }
  },
  created() {
    this.loadCateList()
    this.loadArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
/deep/ .ql-editor {
  height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
